/*
 * Sudoku4 interface functions
 * 
 * @author Patricia Grao
 */



var squareEnabledBkColor = "#fff";
var squareDisabledBkColor = "#ebebeb";
var squareSelectedBkColor = "#a1ff97";
var squareHelpBkColor = "#FFCC66";


window.wicketGlobalPreCallHandler = function() {
	$("#veil").css('display', 'block');
};

window.wicketGlobalPostCallHandler = function() {
	$("#veil").css('display', 'none');
};


function returnChangeBox(id){    
	$("[id='" + id + "']").css('background-color', squareSelectedBkColor);
	$('#keyboard').hide();
}


function hideDivHelp(){
	$('#help').hide('puff', null, 1000, function() {$('#buttonHelpHide').show('explode', null, 500)});
}


function showDivHelp(){
	$('#buttonHelpHide').hide('puff', null, 1000, function() {$('#help').show('explode', null, 500)});
}


function showWin(){
	
	$("#checkButtom").children("input[type='submit']:first").hide();
	$("#blockWin").hide();

	var posFirst = $("#panelrow0 input:first-child").position();
	var posLast = $("#panelrow3 input:last-child").position();

	var topMiddle = (posLast.top - posFirst.top)/2;
	var leftMiddle = (posLast.left - posFirst.left)/2;
	
	// reset properties of box win
    $('#blockWin').css({
      top: posFirst.top + topMiddle,
      left: leftMiddle,
      borderWidth: '10px',
      width: (posLast.left - posFirst.left) + 'px',
      fontSize: '1.5em'
    })
	$(".box").css('background-color', '#FFCC33');
	$(".box").fadeTo(1500, 0.6, 
			function () { $("#blockWin").slideDown(1500)});
}


/**
 * Function executed on ajax callback
 * @param id The id of the input element whose change invoked the Ajax call.
 */
function processServerResponse(id) {
	returnChangeBox(id);
	showHelp(id);
}

/**
 * Function executed on ajax callback to show message help
 * @param id The id of the input element whose change invoked the Ajax call.
 */
function processServerResponseHelpColor(id){  
	$("[id='" + id + "']").css('background-color', squareHelpBkColor);
}

/**
 * Shows a popup bubble with the feedback received from the server.
 */
function showHelp(id){
	
	var distance = 10;
    var time = 600;
    
    var inputSquare = $("[id='" + id + "']");
    
    if ( $("#feedback > *").size() > 0 ){
    	
    	// Remove square information from the messages
    	var messages = $('#feedback > ul > li > span');
    	
    	for (var i = 0; i < messages.length; i++) {
    		var msg = $(messages[i]).text();
    		msg = msg.slice(msg.indexOf(":")+2);
    		$(messages[i]).text(msg);
    	}
    
		var pos = inputSquare.offset();
		
		// reset position of popup box
	    $('.popup').css({
	    	top: pos.top - $('.popup').outerHeight() + 40,
	    	left: pos.left - ($('.popup').width()/2) + (inputSquare.outerWidth()/2),
	    	display: 'block' // brings the popup back in to view
	    });
	
	    // (we're using chaining on the popup) now animate it's opacity and position
	    $('.popup').animate({
	    	top: '-=' + distance + 'px',
	    	opacity: 0.9
	    }, time);

    }
    
    // Update mouse cursors
    updateMouseCursors();
}


/**
 * Highlights all the peer squares of the clicked squared
 * @param e The event
 */
function changeColor(e) {
	
	e.stopPropagation();
	
	var arrayName = null;
	var objectAnimation = null;
      
	var arrayRow = ["1","2","3","4"];
	var arrayCol = ["A","B","C","D"];

	var id = this.name;
	lastId = id;
      
	arrayName= id.split("",2);

	//initialize
	restoreInputColors();
	$('.popup').hide();
      
	//row
	for (i=0; i < 4; i++){
		objectAnimation = arrayName[0]+arrayRow[i];	
		$("[name='" +objectAnimation + "']").css('background-color', squareSelectedBkColor);
	}
  
	//col
	for (j=0; j < 4; j++){
		objectAnimation = arrayCol[j]+arrayName[1];	   		
	    $("[name='" +objectAnimation + "']").css('background-color', squareSelectedBkColor);
	}

	//box
	if (arrayName[0] == 'A' || arrayName[0] == 'C'){
		objectAnimation = arrayCol[arrayCol.indexOf(arrayName[0])+1];
	}else{ // B || D
		objectAnimation = arrayCol[arrayCol.indexOf(arrayName[0])-1];		      
	}

	if (arrayName[1] == '1' || arrayName[1] == '3'){
		objectAnimation = objectAnimation + arrayRow[arrayRow.indexOf(arrayName[1])+1];
	}else{ // 2 || 4
		objectAnimation = objectAnimation + arrayRow[arrayRow.indexOf(arrayName[1])-1];		      
	}

	$("[name='" +objectAnimation + "']").css('background-color', squareSelectedBkColor);
}


/**
 * Shows an on-screen keyboard to fill a square
 * @param e The event
 */
function inputKeyboard(e) {
	
	var id = this.name;
	var pos = $("[name='" + id + "']").offset();
	
    $('#keyboard').hide();

    $('#keyboard').css({
    	top: pos.top - 5,
    	left: pos.left - 10,
	}).toggle();
    
}


/**
 * Sets the mouse cursor as a pointer on enabled squares and as default on
 * disabled ones.
 */ 
function updateMouseCursors() {
	$('.box:enabled').css('cursor', 'pointer');
	$('.box:disabled').css('cursor', 'default');
}


/**
 * Repaints the inputs with the appropiate colors
 */
function restoreInputColors() {
	$('.box:enabled').css('background-color', squareEnabledBkColor);
	$('.box:disabled').css('background-color', squareDisabledBkColor);
}


/**
 * Function executed when the DOM has loaded.
 */
$(document).ready(function() {	

	//only visible if javascript is not enabled
	$("#checkButtom").children("input[type='submit']:first").hide();
	
	// Stop Firefox from painting failed values in non-set squares
	var enabledSquares = $(".box:enabled");
	for ( var i=0; i<enabledSquares.length; i++ ) {
		$(enabledSquares[i]).val("");
	}
	
	restoreInputColors();
	
	$("#keyboard input").bind("click", function(e) {
		e.stopPropagation();
		$('#keyboard').hide();
		$("[name='" + lastId + "']").val($(this).val());		
		$("[name='" + lastId + "']").focus();
		$("[name='" + lastId + "']").change();
	});
	
	
	// When clicking the body
	$('body').live('click', function(e) {
		if ( !e.isPropagationStopped() ) {
			
			// Restore seduku colors
			restoreInputColors();
			
			// Hide keyboard
			$('#keyboard').hide();
		}
	});
	
	// When clicking a square
	$(".box").live("click", changeColor);
	$(".box").live("click", inputKeyboard);
	
	$(".popup").live("click", function(){ $(".popup").hide() });
	$("#help").draggable();
	$("#close").live("click", hideDivHelp);
	$("#buttonHelp").live("click", showDivHelp);
	
	updateMouseCursors();
		
});